package com.xhui.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhui.reggie.common.R;
import com.xhui.reggie.entity.User;
import com.xhui.reggie.service.UserService;
import com.xhui.reggie.utils.SMSUtils;
import com.xhui.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * Author XHui
 * Date 2023/1/19 9:56
 * Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 给指定手机发送短信验证码
     * @param user 前端数据
     * @return 是否成功
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        if (userService.sendMsg(user)) {
            return R.success("手机验证码发送成功");
        }
        return R.error("手机验证码发送失败");
    }

    /**
     * 移动端用户登录
     * @param map 手机号、验证码
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request){
        // 获取手机号 和 验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        if(!userService.checkValidateCode(phone, code)){
            // 比对失败
            return R.error("登录失败");
        }
        // 比对成功
        // 若为新用户，默认给他注册
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(userLambdaQueryWrapper);
        if (user == null){
            // 属于新用户，默认给他注册了
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        request.getSession().setAttribute("user", user.getId());
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        // 清除服务器中的已存储的session 键值对
        request.getSession().removeAttribute("user");
        return R.success("用户退出登录成功");
    }

}
